<template>
  <div :class="className" :style="{ height: height, width: width }" id="eChart"/>
</template>

<script>
import echarts from 'echarts'
import elementResizeDetectorMaker from 'element-resize-detector'
require('echarts/theme/macarons') // echarts theme
import resize from '@/components/mixins/resize'

// const animationDuration = 6000

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '450px'
    },
    chartData: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    const that = this
    var echart = document.getElementById('eChart')
    this.$nextTick(() => {
      this.initChart()
    })
    var erd = elementResizeDetectorMaker()
    erd.listenTo(echart, function() {
      that.$nextTick(function() {
        echarts.init(echart).resize()
      })
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions(this.chartData)
    },
    setOptions(chartData) {
      // console.log(chartData)
      const data = chartData
      const dataName = []
      const dataValue = []
      for (const i in data) {
        dataName.push(data[i].name)
        dataValue.push(data[i].value)
      }
      this.chart.setOption({
        color: ['#3398DB'],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          top: 30,
          left: 30,
          right: 30,
          bottom: 70,
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            axisLabel: {
              interval: 0
            },
            data: dataName,
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        dataZoom: {
          show: true,
          realtime: true,
          y: 400,
          height: 50,
          start: 100,
          end: 0
        },
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '出库数量',
            type: 'bar',
            barWidth: '60%',
            data: dataValue
          }
        ]
      })
    }
  }
}
</script>
